#include "EncoderPAD.h"

typedef enum
{
    KeyState_idle = 0x00,
    KeyState_reduction,
    KeyState_tick,
}KeyState;

#define KEY_PRESS_SHORT_TICK(x) (x>5&&x<50)
#define KEY_PRESS_LONG_TICK(x)  (x>50)

uint16_t key_pin[ALL_KEY_NUM] = {PAD_S_Pin, USER_KEY1_Pin};
GPIO_TypeDef* key_port[ALL_KEY_NUM] = {PAD_S_GPIO_Port, USER_KEY1_GPIO_Port};
KeyState key_state[ALL_KEY_NUM] ={KeyState_idle};
uint16_t key_tick[ALL_KEY_NUM] ={0};
KeySta key[ALL_KEY_NUM] = {KS_none};

void KEY_Scan(void)
{
    for(uint8_t i =0; i < ALL_KEY_NUM; i++)
    {
        switch (key_state[i])
        {
            case KeyState_idle:
                if(HAL_GPIO_ReadPin(key_port[i],key_pin[i]) == GPIO_PIN_RESET)key_state[i] = KeyState_reduction;
                break;
            case KeyState_reduction:
                if(HAL_GPIO_ReadPin(key_port[i],key_pin[i]) == GPIO_PIN_RESET)key_state[i] = KeyState_tick;
                break;
            case KeyState_tick:
                if(HAL_GPIO_ReadPin(key_port[i],key_pin[i]) == GPIO_PIN_RESET)
                {
                    key_tick[i]++;
                    if(KEY_PRESS_LONG_TICK(key_tick[i]))key[i] = KS_long_hold;
                }
                else
                {
                    if(KEY_PRESS_SHORT_TICK(key_tick[i]))key[i] = KS_short_release;
                    if(KEY_PRESS_LONG_TICK(key_tick[i]))key[i] = KS_long_release;
                    key_tick[i] = 0;
                    key_state[i] = KeyState_idle;
                }
                break;
            default:break;
        }
    }
}

KeySta KEY_Read(KeyId key_id)
{
    KeySta temp_ks = key[key_id]; 
    key[key_id] = KS_none;
    return temp_ks;
}
